<?php
namespace App\Api\Controllers\Ccb;


use App\Models\Ad;
use App\Models\User;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;

class BaseController extends \App\Api\Controllers\BaseController
{
    // 表单提交字符集编码
    public $postCharset = "UTF-8";

    private $fileCharset = "UTF-8";


    //参数拼接
    public function getSignContent($params)
    {
        ksort($params);

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    //增加退款订单
    function add_refund_orders($refund_no,$out_trade_no,$refund_amount){
        $order=DB::table('orders')->where('out_trade_no',$out_trade_no)->select('store_id','created_at')->first();
        $data=array('refund_no'=>$refund_no,'refund_amount'=>$refund_amount,'out_trade_no'=>$out_trade_no,'store_id'=>$order->store_id,'refund_time'=>date('Y-m-d H:i:s',time()),'created_at'=>$order->created_at);
        
        $refund_order=DB::table('all_refund_orders')->where('out_trade_no',$out_trade_no)->select('store_id','created_at')->first();
        if(empty($refund_order)){
            DB::table('all_refund_orders')->insert($data);
        }
    }
    
    /**
     * 按key升序排序，同时去掉空值
     * @param $params array
     * @return mixed
     */
    public function sortParams($params) {
        ksort($params);
        foreach ($params as $key => $value) {
            if (empty($value) && $value == '') {
                unset($params[$key]);
            }
        }
        return $params;
    }
    
    /**
     * 计算签名
     * @param $params array 不含空值
     * @return string
     */
    public function calSign($params) {
        return md5(http_build_query($params) .'20120315201809041004');
    }
    
    /**
     * 计算ccbparam
     * @param $params string
     * @param $key string
     * @return string
     */
    public function calCcbParam($params, $key) {
        $res = openssl_encrypt (iconv("utf-8", "utf-16", $params), 'DES-ECB', $key);
        $res = str_replace('+', ',', $res);
        $res = urlencode($res);

        return $res;
    }
    
    //参数拼接
    public function getSignContent1($params)
    {

        $stringToBeSigned = "";
        $i = 0;
        foreach ($params as $k => $v) {
            if (false === $this->checkEmpty($v) && "@" != substr($v, 0, 1)) {
                // 转换成目标字符集
                $v = $this->characet($v, $this->postCharset);

                if ($i == 0) {
                    $stringToBeSigned .= "$k" . "=" . "$v";
                } else {
                    $stringToBeSigned .= "&" . "$k" . "=" . "$v";
                }
                $i++;
            }
        }

        unset ($k, $v);
        return $stringToBeSigned;
    }
    
    //处理xml实体
    public function getXmlContent($data){
        $string = '';
        foreach ($data as $k => $v) {
            $string.='<'.$k.'>'.$v.'</'.$k.'>';
        }
        $string='<Message>'.$string.'</Message>';
        return $string;
    }
    
     //翼支付私钥加密
    // public function createSign4($data){
    //     file_put_contents('yi4574.log',var_export($data,true)."\r\n",FILE_APPEND);
    //     $pfx=file_get_contents('https://pay.zgjindoufu.com/安徽淮风文化传媒有限公司.P12');
    //     $cert_info=array();
    //     $priKey=openssl_pkcs12_read($pfx,$cert_info,'97445505');
        
    //     openssl_sign($data, $sign, $cert_info['pkey'],OPENSSL_ALGO_SHA256);
    //     return base64_encode($sign);
    // }
    
    //甘肃农商行私钥加密
    public function createSign1($xml){
        $pfx=file_get_contents('https://pay.zgjindoufu.com/ddbank_test.pfx');
        $cert_info=array();
        openssl_pkcs12_read($pfx,$cert_info,'123456');
        $pkey=openssl_pkey_get_private($cert_info['pkey']);
        openssl_sign($xml, $sign, $pkey,OPENSSL_ALGO_MD5);
        return bin2hex($sign);
    }

    public function allin_sign(array $array,$prikey){
        ksort($array);
        $bufSignSrc = $this->allin_Params($array);
        $private_key = chunk_split($prikey , 64, "\n");
        $key = "-----BEGIN RSA PRIVATE KEY-----\n".wordwrap($private_key)."-----END RSA PRIVATE KEY-----";
        openssl_sign($bufSignSrc, $signature, $key);
        $sign = base64_encode($signature);
        return $sign;
    }

    public function allin_Params(array $array){
        $buff = "";
        foreach ($array as $k => $v)
        {
            if($v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

    public function allin_request($url,$params){
        $ch = curl_init();
        $this_header = array("content-type: application/json; charset=UTF-8;");
        curl_setopt($ch,CURLOPT_HTTPHEADER,$this_header);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);

        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//如果不加验证,就设false,商户自行处理
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);

        $output = curl_exec($ch);
        curl_close($ch);
        return  $output;
    }


    /**
     * 转换字符集编码
     * @param $data
     * @param $targetCharset
     * @return string
     */
    function characet($data, $targetCharset)
    {
        if (!empty($data)) {
            $fileType = $this->fileCharset;
            if (strcasecmp($fileType, $targetCharset) != 0) {
                $data = mb_convert_encoding($data, $targetCharset);
                //$data = iconv($fileType, $targetCharset.'//IGNORE', $data);
            }
        }

        return $data;
    }


    /**
     * 校验$value是否非空
     * if not set ,return true;
     * if is null , return true;
     **/
    protected function checkEmpty($value)
    {
        if (!isset($value))
            return true;
        if ($value === null)
            return true;
        if (trim($value) === "")
            return true;

        return false;
    }


    /**
     * curl发送数据
    */
    static function curl($data, $url)
    {
        //启动一个CURL会话
        $ch = curl_init();
        // 设置curl允许执行的最长秒数
        curl_setopt($ch, CURLOPT_TIMEOUT, 120);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

        //发送一个常规的POST请求。
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_URL, $url);
        //要传送的所有数据
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);

        // 执行操作
        $res = curl_exec($ch);
        $response = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        if ($res == NULL) {
            curl_close($ch);
            return false;
        } else if ($response != "200") {
            curl_close($ch);
            return false;
        }

        curl_close($ch);

        return $res;
    }


    function curl_get($url)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //绕过ssl验证
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);

        //执行并获取HTML文档内容
        $output = curl_exec($ch);

        //释放curl句柄
        curl_close($ch);

        return $output;
    }


    /**
     * 校验必填字段
     */
    public function check_required($check, $data)
    {
        $rules = [];
        $attributes = [];

        foreach ($data as $k => $v) {
            $rules[$k] = 'required';
            $attributes[$k] = $v;
        }

        $messages = [
            'required' => ':attribute不能为空',
        ];
        $validator = Validator::make($check, $rules, $messages, $attributes);
        $message = $validator->getMessageBag();

        return $message->first();
    }


    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
//        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }
    
    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl3($url, $post_data)
    {
//        file_put_contents('1235.log',var_export($post_data,true)."\r\n",FILE_APPEND);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);
//                                    file_put_contents('1235.log',var_export($output,true)."\r\n",FILE_APPEND);
        //返回数据
        return $output;
    }

    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl22($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_TIMEOUT, 3);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/json',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
        curl_close($ch);

        //返回数据
        return $output;
    }

    /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    function http_curl1($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);

        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); // post的变量
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Content-Type: application/x-www-form-urlencoded',
                'Content-Length: ' . strlen($post_data)
            )
        );
        $output = curl_exec($ch);
//        file_put_contents('ceshi.log',var_export($output,true)."\r\n",FILE_APPEND);
        curl_close($ch);

        //返回数据
        return $output;
    }
    
    public function doPost($url, $params, $charset){
			$headers = array();
			$headers[] = 'Expect:';
			$headers['APIGW-VERSION'] = 'v2_20170324';
//file_put_contents('icbcce.log',var_export(http_build_query($params),true)."\r\n",FILE_APPEND);
		    $ch = curl_init();
		    curl_setopt($ch, CURLOPT_URL, $url);
		    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
		    curl_setopt($ch, CURLOPT_POST, true);
		    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($params));
		    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

		    curl_setopt($ch, CURLOPT_NOSIGNAL, 1);
		    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS,8000);
		    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 30000);
		    curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
		    curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);


		    $response = curl_exec($ch);
		    //file_put_contents('icbcce.log',var_export($response,true)."\r\n",FILE_APPEND);
		    $resinfo = curl_getinfo($ch);
		    curl_close($ch);

		    if($resinfo["http_code"] != 200){
		    	throw new Exception("response status code is not valid. status code: ".$resinfo["http_code"]);
		    }
			return $response;
	   }
	   
	   public function buildOrderedSignStr($path,$params){
	   		$isSorted=ksort($params);
	   		$comSignStr = $path.'?';
	   		$hasParam = false;
	   		foreach ($params as $key => $value) {
	   			if(null == $key || "" == $key || null == $value || ""==$value){

	   			}else{
	   				if ($hasParam) {
	   					$comSignStr=$comSignStr.'&';
	   				}else{
	   					$hasParam=true;
	   				}
	   				$comSignStr=$comSignStr.$key.'='.$value;
	   			}
	   		}
	   		return $comSignStr;
	   }

     /**
     * http的curl 方法post请求接口
     * @param string $url
     * @param string $post_data
     * @return string
     */
    public function gshttp_curl($url, $post_data)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1); // post数据
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
        curl_setopt ( $ch, CURLOPT_POSTFIELDS, http_build_query($post_data));
        $output = curl_exec($ch);
        curl_close($ch);
        
        $data=simplexml_load_string($output,"SimpleXMLElement", LIBXML_NOCDATA);
        $data = json_decode(json_encode($data),true);
        $data = explode('|', $data['Plain']);
        $array=array();
        foreach($data as $k=>$v){
            if(!empty($v)){
                $list=explode('=', $v);
                $array[$list[0]]=$list[1];
            }
        }
        //返回数据
        return json_encode($array);
    }

}
